'''
Target: Python AndroidToolBox ScreenProjection Module
Author: LZR@BUAA
Date:   08/26/2020
'''
import datetime
import os
import time

from ADBMethods import *
from SysMethods import *

# import adb_shell.adb_device
path = os.getcwd()
conf = []
config = ''

# 仍然要考虑多个手机情况以及配置自动化


def initializeConfig():
    global config
    if os.access("Scrcpy-Settings.txt", os.F_OK):
        settings = open("Scrcpy-Settings.txt", "r")
        if settings.read(6) == "scrcpy":
            print("是否以上一次的配置启动？(Y/N)")
            settings.seek(0, 0)
            if InputJudge(2):
                config = settings.read()
                return
    configGenerator()


def configGenerator():
    conf.append("scrcpy --window-title \""+ MobileInfo['model'] +" LZR@BUAA\"")
    print("关闭手机屏幕？(Y/N)")
    if InputJudge(2):
        conf.append(" -S")

    print("主界面置顶？(Y/N)")
    if InputJudge(2):
        conf.append(" --always-on-top")

    print("启动屏幕录制？(Y/N)")
    if InputJudge(2):
        tm = time.strftime("%Y%m%d_%H%M%S", time.localtime())
        conf.append(" -r "+path+"\\ScreenRecords\\SccreenRecord" + tm + ".mp4")

    print("全屏显示？(Y/N)")
    if InputJudge(2):
        conf.append(" -f")

    pixels = ['', '', '1920', '1440', '1080']
    print("分辨率设置(原始比例)：\n[1]默认\n[2]1920\n[3]1440\n[4]1080")
    op = InputJudge(4)
    if op in [2, 3, 4]:
        conf.append(" -m "+pixels[int(op)])

    BitRate = ['', '20M', '10M', '8M', '4M', '2M']
    print(
        "比特率设定(数值越大画质越好，延迟越大)：\n[1]20Mbps\n[2]10Mbps\n[3]8Mbps(默认)\n[4]4Mbps\n[5]2Mbps")
    op = InputJudge(5)
    conf.append(" -b "+BitRate[int(op)])

    global config
    config = ''.join(conf)
    # print("是否保存此次配置？(Y/N)")
    # if InputJudge(2):
    settings = open("Scrcpy-Settings.txt", "w")
    settings.write(config)
    settings.close()
    print("当前配置已保存！")

    print("是否显示操作指南？(Y/N)")
    if InputJudge(2):
        os.startfile("tutor.png")


def USBconnect(config):
    cmd(config)


def WLANconnect(config):
    # print("Wlan")
    IP = getIPaddress()
    # print(IP)
    if cmd("adb tcpip 5555").find("error") == -1:
        input("现在已经可以断开设备……断开连接后请按Enter")
        r = cmd("adb connect " + IP)
        if r.find("unable") == -1:
            USBconnect(config)
# 处理是否连接
    else:
        print("设备连接失败！程序退出中……")
        exit()


def Screenmain():
    print("########################################")
    print("")
    print("             Scrcpy投屏工具")
    print("              By:LZR@BUAA")
    print("")
    print("########################################")
    print("欢迎使用!\n请连接手机并开启USB调试模式 MIUI还需开启USB调试(安全设置)……")
    cmd("adb disconnect")
    while True:
        if USBConnected():
            if powerStatus():
                getInfo()
                print("手机连接成功！当前设备： " +
                      MobileInfo['brand'] + " " + MobileInfo['model'])
                break
            else:
                print("手机开机状态异常，是否重新开机？(Y/N)")
                while True:
                    op = input()
                    if op in ['Y', 'y']:
                        cmd("adb reboot")
                    break
        time.sleep(2)

    print("请选择需要的配置")
    initializeConfig()

    print("选择连接模式：")
    print("[1]通过USB方式连接")
    print("[2]通过网络连接")

    while True:
        op = input("请输入选项，按Enter键结束：")
        if op != '1' and op != '2':
            print("无效输入，请重新输入!")
        else:
            if op == '1':
                USBconnect(config)
                break
            if op == '2':
                WLANconnect(config)
                break
    print("程序已关闭，即将退出……")
    exit()

if __name__ == "__main__":
    Screenmain()
